#coding=utf-8
import sys
import wx
import wx.html
import wx.aui

import env
import data
import db
from ids import *
import wx.lib.pubsub as ps
 
class MainFrame(wx.Frame):
    
    def __init__(self, parent, id=-1, title="", pos=wx.DefaultPosition,
                 size=(980, 700), style=wx.DEFAULT_FRAME_STYLE |
                                            wx.SUNKEN_BORDER |
                                            wx.CLIP_CHILDREN):
        wx.Frame.__init__(self, parent, id, title, pos, size, style)
        
        pnl = wx.Panel(self)
        self.pnl = pnl
        
        # create menu
        mb = wx.MenuBar()

        file_menu = wx.Menu()
        file_menu.Append(wx.ID_EXIT, "Exit")

        edit_menu = wx.Menu()
        edit_menu.AppendSeparator();
        
        account_menu = wx.Menu()
        account_menu.AppendSeparator();
        
        data_menu = wx.Menu()
        data_menu.AppendSeparator();
        
        tools_menu = wx.Menu()
        tools_menu.AppendSeparator();
        
        help_menu = wx.Menu()
        help_menu.Append(ID_About, "About...")
        
        mb.Append(file_menu, "File")
        mb.Append(edit_menu, "Edit")
        mb.Append(account_menu, "Account")
        mb.Append(data_menu, "Account")
        mb.Append(tools_menu, "Data")
        mb.Append(help_menu, "Help")
        
        self.SetMenuBar(mb)
        
        #create statusar
        self.statusbar = self.CreateStatusBar(2, wx.ST_SIZEGRIP)
        self.statusbar.SetStatusWidths([-2, -3])
        self.statusbar.SetStatusText("Ready", 0)
        self.statusbar.SetStatusText("Welcome To adwords", 1)

        # min size for the frame itself isn't completely done.
        # see the end up FrameManager::Update() for the test
        # code. For now, just hard code a frame minimum size
        self.SetMinSize(wx.Size(400, 300))

        # create some toolbars
        
        tb = self.CreateToolBar()#wx.TB_HORIZONTAL|wx.NO_BORDER)
        
        
        tb.AddLabelTool(ID_ADD, "Add A Campaign or AD", wx.Bitmap('./images/add.png'), 
                        shortHelp="Add A Campaign or AD")
        
        tb.AddLabelTool(ID_REMOVE, "Remove A Campaign or AD", wx.Bitmap('./images/remove.png'), 
                        shortHelp="Remove A Campaign or AD")
        tb.AddSeparator()
        tb.AddLabelTool(ID_DOWNLOAD, "Update Campaign Info", wx.Bitmap('./images/down.png'),
                        shortHelp="Update Campaign Info")
        tb.AddLabelTool(ID_UPLOAD, "Upload Changes", wx.Bitmap('./images/up.png'),
                        shortHelp="Upload Changes")
        tb.AddSeparator()
        tb.AddLabelTool(ID_STATIC, "View Statitics Info", wx.Bitmap('./images/static.png'),
                        shortHelp="View Statitics Info")
        tb.Realize()
        
        self.Bind(wx.EVT_TOOL, self.OnAdd, id=ID_ADD)
        disable_ids = [ID_REMOVE, ID_DOWNLOAD, ID_UPLOAD, ID_STATIC]
        for i in disable_ids:
            tb.EnableTool(i, False)
            
        #Left Tree
        self.tree = wx.TreeCtrl(self.pnl)
        root = self.tree.AddRoot("Campaigns")
        self.AddTreeNodes(root, env.generate_camp_tree())
        self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnActived, self.tree)
        
        #centre listctrl
        self.list = wx.ListCtrl(pnl, -1, style=wx.LC_REPORT)
        
        self.bp = None
        self.ap = None
        # tell FrameManager to manage this frame        
        self.mgr = wx.aui.AuiManager()
        self.mgr.SetManagedWindow(self.pnl)
        
        self.mgr.AddPane(self.tree,
                         wx.aui.AuiPaneInfo().
                         Left().Layer(2).BestSize((240, -1)).
                         MinSize((160, -1)).
                         Floatable(False).
                         Caption("Campaign Information").
                         CloseButton(False).
                         Name("Tree"))
        self.mgr.AddPane(self.list, wx.aui.AuiPaneInfo().CenterPane().Name("list"))
        
        self.mgr.Update()
        
        self.AddCampPane = None
        
    def AddTreeNodes(self, parentItem, items):
        """
        Recursively traverses the data structure, adding tree nodes to
        match it.
        """
        
        for item in items:
            if type(item) == str or type(item) == type(u'jay'):
                self.tree.AppendItem(parentItem, item)
            else:
                newItem = self.tree.AppendItem(parentItem, item[0])
                self.AddTreeNodes(newItem, item[1])
                
    def SetListCtrl_byCamp(self, camp):
        self.list.ClearAll()
        
        self.list.InsertColumn(0, 'Name', width=100)
        self.list.InsertColumn(1, 'Budget', width=100)
        self.list.InsertColumn(2, 'Status', width=100)
        self.list.InsertColumn(3, 'Start_on', width=100)
        self.list.InsertColumn(4, 'end_on', width=100)
        self.list.InsertColumn(5, 'description', width=400)
        
        index = self.list.InsertStringItem(0, camp.name)
        self.list.SetStringItem(index, 1, str(camp.budget))
        self.list.SetStringItem(index, 2, camp.status)
        self.list.SetStringItem(index, 3, camp.start_on.isoformat())
        self.list.SetStringItem(index, 4, camp.end_on.isoformat())
        self.list.SetStringItem(index, 5, camp.description)
    
    def OnActived(self, event):
        name = self.tree.GetItemText(event.GetItem())
        
        c = db.find_camp(env.current_user.name, name)
        if c:
            ps.Publisher.sendMessage('Camp.Selected', c)
                       
        else:
            a = db.find_ad(env.current_user.name, name)
            ps.Publisher.sendMessage('Ad.Selected', a)
           
     
    def OnAdd(self, event):
        self.Enable(False)
        
        if not self.AddCampPane:
            self.AddCampPane = gcamp.CampFrame(self)
        
        self.AddCampPane.Show(True)
            
           
if __name__ == '__main__':
    from handler import * 
    app = wx.PySimpleApp()
    
    frm = MainFrame(None)
    
    frm.Centre()
    frm.Show()
    
    env.mainFrame = frm
    frm.tree.SelectItem(frm.tree.GetFirstChild(frm.tree.GetRootItem())[0])
    ps.Publisher.sendMessage('Camp.Selected', env.current_camp)
    app.MainLoop()
